﻿using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Web.ModelBinding;

namespace Morus.Presentation
{
    public sealed class NamingControlValueProvider : NameValueCollectionValueProvider
    {
        public NamingControlValueProvider(ModelBindingExecutionContext modelBindingExecutionContext)
            : this(modelBindingExecutionContext.HttpContext.Request.Form, modelBindingExecutionContext.HttpContext.Request.Unvalidated.Form)
        {

        }

        internal NamingControlValueProvider(NameValueCollection collection, NameValueCollection unvalidatedCollection)
            : base(CleanNamingControl(collection), CleanNamingControl(unvalidatedCollection), CultureInfo.CurrentCulture)
        {
        }

        private static NameValueCollection CleanNamingControl(NameValueCollection namingControlCollection)
        {
            NameValueCollection result = new NameValueCollection();
            if (namingControlCollection != null && namingControlCollection.AllKeys != null && namingControlCollection.AllKeys.Length > 0)
            {
                namingControlCollection.AllKeys.ToList().ForEach(controlName =>
                {
                    if (controlName.IndexOf('$') > 0)
                    {
                        var cleanKey = controlName.Split("$".ToArray(), StringSplitOptions.RemoveEmptyEntries).Last();
                        var values = namingControlCollection.GetValues(controlName);
                        values.ToList().ForEach(v =>
                        {
                            result.Add(cleanKey, v);
                        });
                    }
                });
            }
            return result;
        }
    }
}
